package topic

import (
	"sync"
	"time"
	"wths/wthsjy-im/plugins/log"
	"wths/wthsjy-im/server/handle"
)

var (
	topicsManagerOnce sync.Once
	topicMgr          *TopicsManager
)

type TopicsManager struct {
	store sync.Map
}

// NewTopicsManager 新建topic 管理器
func NewTopicsManager() *TopicsManager {
	topicsManagerOnce.Do(func() {
		topicMgr = &TopicsManager{}
	})
	return topicMgr
}

// Bind topic-client 建立绑定关系
func (mgr *TopicsManager) Bind(topicName string, cli handle.ClientHandle) {
	log.Debug("Bind1111").Msg(cli.ClientID())

	t, exist := mgr.store.Load(topicName)
	if !exist {
		log.Debug("Bind1111").Msg(cli.ClientID(), "bucket 里不存在cli")
		t = &topic{
			topicName: topicName,
		}
		mgr.store.Store(topicName, t)
	}
	_ = t.(*topic).add(cli)
}

// Unbind topic-client 解除绑定关系
func (mgr *TopicsManager) Unbind(topicName string, cli handle.ClientHandle) {
	log.Debug("Unbind_1").Msg(cli.ClientID())

	t, exist := mgr.store.Load(topicName)
	log.Debug("###Unbind_2").Msg(cli.ClientID(), "bucket exist：", exist)

	if !exist {
		log.Debug("###Unbind_3").Msg(cli.ClientID(), "bucket 里不存在cli")
		return
	}
	clientNum := t.(*topic).remove(cli)

	// 移除空对象
	if clientNum == 0 {
		log.Debug("###Unbind_4").Msg(cli.ClientID(), topicName, "清空")
		mgr.store.Delete(topicName)
	}
}

// PushMessageToTopic 推送消息
func (mgr *TopicsManager) PushMessageToTopic(topicName string, data []byte) {
	t, exist := mgr.store.Load(topicName)
	if !exist {
		log.Debug("###@Write~~").Msg("nnnuuulll", time.Now().String())
		return
	}
	t.(*topic).pushMessage(data)
}
